<template>
  <div class="content">
    <div class="title">
      <div class="titleContent">
        产品类目管理
      </div>
      <div class="add-button">
        <el-button type="warning" class="" @click="showDialog('addTopLevel')">新增一级分类</el-button>
      </div>
    </div>

    <div class="custom-tree-container">
      <div class="block">
        <el-tree :data="categoryList" show-checkbox node-key="id" default-expand-all :expand-on-click-node="false"
          :render-content="renderContent">
        </el-tree>
      </div>
    </div>

    <!-- Form -->

    <el-dialog :title="dialogForm.title" :visible.sync="dialogFormVisible" width="400px">
      <el-form :model="dialogForm" ref="dialogForm" :rules="rules">
        <el-form-item label="分类名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="dialogForm.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button @click="handleAddCategory()" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="deleteDialogVisible" width="30%">
      <span>确定要删除吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelDelete">取 消</el-button>
        <el-button type="primary" @click="handDelete">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getCategoryList, addCategory, editCategory, deleteCategory } from '@/api/category.js'
let id = 14
export default {
  data() {
    return {
      categoryList: [
        { id: 1, label: '一级 1', children: [{ id: 4, label: '二级 1-1', children: [{ id: 9, label: '三级 1-1-1' }, { id: 10, label: '三级 1-1-2' }] }] },
        { id: 2, label: '一级 2', children: [{ id: 5, label: '二级 2-1' }, { id: 6, label: '二级 2-2' }] }
      ],
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '80px',
      dialogForm: {
        title: '',
        type: '',
        name: '',
        id: -1,
        pid: -1,
        level: -1,
        children: []
      },
      rules: {
        name: [{ required: true, message: '请输入分类名', trigger: 'blur' }],
      },
      deleteDialogVisible: false,
      tempData: {},
      deleteData: {}
    }
  },
  created() {
    this.getCategoryArr()
  },

  methods: {
    // 显示新增类目对话框
    showDialog(title, data) {
      if (data) {
        this.tempData = data
      }
      this.dialogFormVisible = true
      if (title === 'addTopLevel') {
        this.dialogForm.title = '新增一级分类'
        this.dialogForm.type = 'addTopLevel'
      }
      else if (title === 'editTopLevel') {
        this.dialogForm.title = '修改分类名称'
        this.dialogForm.type = 'editTopLevel'
        this.dialogForm.name = data.label
      }
      else if (title === 'addSecondLevel') {
        this.dialogForm.title = '新增二级分类'
        this.dialogForm.type = 'addSecondLevel'
      }
      else if (title === 'editSecondLevel') {
        this.dialogForm.title = '修改分类名称'
        this.dialogForm.type = 'editSecondLevel'
        this.dialogForm.name = data.label
      }
    },
    handleAddCategory() {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          //新增一级分类
          if (this.dialogForm.type == 'addTopLevel') {
            let category = { pid: 0, level: 0, name: this.dialogForm.name }
            addCategory(category).then(res => {
              if (res.data) {
                this.resetDialogForm()
                this.getCategoryArr()
                this.$showSuccessMsg('添加成功')
              }
            })
          }
          // 新增二级分类
          else if (this.dialogForm.type === 'addSecondLevel') {
            let category = { pid: this.tempData.id, level: this.tempData.level + 1, name: this.dialogForm.name }
            addCategory(category).then(res => {
              if (res.data) {
                this.resetDialogForm()
                this.getCategoryArr()
                this.$showSuccessMsg('添加成功')
              }
            })

          }
          // 编辑一级分类
          else if (this.dialogForm.type === 'editTopLevel') {
            let category = { id: this.tempData.id, name: this.dialogForm.name }
            editCategory(category).then(res => {
              if (res.data) {
                this.resetDialogForm()
                this.getCategoryArr()
                this.$showSuccessMsg('修改成功')
              }
            })
          }
          // 编辑二级分类
          else if (this.dialogForm.type === 'editSecondLevel') {
            let category = { id: this.tempData.id, name: this.dialogForm.name }
            editCategory(category).then(res => {
              if (res.data) {
                this.resetDialogForm()
                this.getCategoryArr()
                this.$showSuccessMsg('修改成功')
              }
            })
          }
        }
      })
    },
    resetDialogForm() {
      this.dialogForm = {}
      this.tempData = {}
      this.dialogFormVisible = false
    },
    
    showDeleteDialog(data) {
      this.deleteData = data;
      this.deleteDialogVisible = true
    },
    handleCancelDelete() {
      this.deleteData = {}
      this.deleteDialogVisible = false
    },
    handDelete() {
      let category = { id: this.deleteData.id, level: this.deleteData.level }
      deleteCategory(category).then(res => {
        if (res.data) {
          this.deleteData = {}
          this.deleteDialogVisible = false
          this.getCategoryArr()
          this.$showSuccessMsg('删除成功')
        }
      })
    },

    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span class="node-name">{node.label}</span>
          <span class="ml100">
            {
              node.level == 1 ?
                <span>
                  <el-button size="mini" on-click={() => this.showDialog('addSecondLevel', data)} icon='el-icon-plus' class="pd-4-7">添加</el-button>
                  <el-button size="mini" on-click={() => this.showDialog('editTopLevel', data)} icon='el-icon-edit' class="pd-4-7">修改</el-button>
                  <el-button size="mini" type="danger" on-click={() => this.showDeleteDialog(data)} icon='el-icon-delete' class="pd-4-7">删除</el-button>
                </span>
                :
                <span>
                  <el-button size="mini" on-click={() => this.showDialog('editSecondLevel', data)} icon='el-icon-edit' class="pd-4-7">修改</el-button>
                  <el-button size="mini" type="danger" on-click={() => this.showDeleteDialog(data)} icon='el-icon-delete' class="pd-4-7">删除</el-button>
                </span>
            }

          </span>
        </span>)
    },
    getCategoryArr() {
      getCategoryList().then(res => {
        const data = res.data

        let oneLevel = data.reduce((acc, category) => {
          if (category.level === 0) {
            acc.push({ id: category.id, pid: category.pid, level: category.level, label: category.name, children: [] })
          }
          return acc
        }, [])

        let twoLevel = data.reduce((acc, category) => {
          if (category.level === 1) {
            acc.push({ id: category.id, pid: category.pid, level: category.level, label: category.name, children: [] })
          }
          return acc
        }, [])

        let threeLevel = data.reduce((acc, category) => {
          if (category.level === 2) {
            acc.push({ id: category.id, pid: category.pid, level: category.level, label: category.name, children: [] })
          }
          return acc
        }, [])

        for (let i = 0; i < oneLevel.length; i++) {
          for (let j = 0; j < twoLevel.length; j++) {
            if (oneLevel[i].id === twoLevel[j].pid) {
              oneLevel[i].children.push(twoLevel[j])
            }
          }
        }
        for (let i = 0; i < twoLevel.length; i++) {
          for (let j = 0; j < threeLevel.length; j++) {
            if (twoLevel[i].id === threeLevel[j].pid) {
              twoLevel[i].children.push(threeLevel[j])
            }
          }
        }

        this.categoryList = oneLevel
      })
    }
  }
}
</script>
<style lang='less' scoped>
.content {
  background-color: #fff;

  .title {
    padding: 10px;
    background-color: #fff;
  }

  .titleContent {
    background-color: #f5f5f5;
    padding: 15px 0 15px 5px;
    font-weight: bolder;
  }
}

::v-deep .add-button {
  margin: 10px 0 0 5px;
}

.custom-tree-container {
  padding-left: 15px;

  ::v-deep .custom-tree-node {
    padding: 5px 0 5px 0;
  }
}

::v-deep .node-name {
  margin-right: 10px;
}

::v-deep .pd-4-7 {
  padding: 4px 7px;
}

::v-deep .ml100{
  margin-left: 100px;
}
</style>